package com.rtmart.imageupload.controller.user;

import com.rtmart.imageupload.domain.Password;
import com.rtmart.imageupload.entity.User;
import com.rtmart.imageupload.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user/")
public class PasswordController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("editPassword")
    public String getEditPassword(Model model){
        model.addAttribute("password", new Password());
        return "user/editPassword";
    }

    @PostMapping("editPassword")
    @Transactional
    public String editPassword(@Validated Password password, BindingResult bindingResult,
                               HttpSession httpSession,HttpServletRequest request, HttpServletResponse response,
                               RedirectAttributes model, Model requestModel){
        if (bindingResult.hasErrors()){
            return "user/editPassword";
        }
        if (!password.getNewPassword().equals(password.getConfirmPassword())){
            bindingResult.rejectValue("confirmPassword", "user.confirmPasswordNotEqualsNewPassword", "新密码2次输入不一致");
            return "user/editPassword";
        }
        /*if (password.getNewPassword().equals(password.getOldPassword())){
            bindingResult.rejectValue("newPassword", "user.oldPasswordEqualsNewPassword", "新密码与原密码相同");
            return "user/editPassword";
        }*/
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        User user = (User)httpSession.getAttribute("user");
        if(!passwordEncoder.matches(password.getOldPassword(), userRepository.findById(user.getId()).getPassword())){
            bindingResult.rejectValue("oldPassword", "user.oldPasswordError", "原密码错误");
            return "user/editPassword";
        }
        String encode = passwordEncoder.encode(password.getNewPassword());
        if (1 == userRepository.updatePassword(encode, user)){
            model.addFlashAttribute("message", "密码修改成功,请重新登录！");
            //httpSession.removeAttribute("user");
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null){
                new SecurityContextLogoutHandler().logout(request, response, auth);
            }
            return "redirect:/login?password";
        }
        requestModel.addAttribute("errorMessage", "密码修改失败！");
        return "user/editPassword";
    }

}
